package org.easyframework.beans.factory.xml;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.easyframework.beans.factory.BeanDefinitionStoreException;
import org.easyframework.beans.factory.support.BeanDefinitionRegistry;
import org.easyframework.beans.factory.support.DefaultBeanFactory;
import org.easyframework.beans.factory.support.GenericBeanDefinition;
import org.easyframework.core.io.ClassPathResource;
import org.easyframework.core.io.Resource;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

public class XmlBeanDefinitionReader {

    private BeanDefinitionRegistry registry;

    public XmlBeanDefinitionReader(BeanDefinitionRegistry registry){
        this.registry=registry;
    }

    public void loadBeanDefinition(Resource resource){

        try {
            InputStream inputStream = resource.getInputStream();
            SAXReader saxReader = new SAXReader();
            Document doc = saxReader.read(inputStream);
            Element root= doc.getRootElement();//beans
            Iterator<Element> iterator = root.elementIterator();
            while(iterator.hasNext()){
                Element element= iterator.next();//bean
                String beanId = element.attributeValue("id");
                String beanClassName = element.attributeValue("class");
                //注册该bean
                GenericBeanDefinition bd = new GenericBeanDefinition(beanId, beanClassName);
                registry.registerBeanDefinition(beanId,bd);
            }
        } catch (Exception e) {
            throw new BeanDefinitionStoreException("IOException parsing XML document from " + resource.getDesciption(),e);

        }


    }

}
